package com.material.mdbook.server;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.material.mdbook.event.ApkFinishEvent;
import com.material.mdbook.event.DownApkEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Objects;

public class DownApkService extends Service {

    private DownloadTask downTask;
    private String TAG = "DownApkService";

    public DownApkService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBus(DownApkEvent event) {
        if (!event.getApkUrl().isEmpty()) {
            startDownApk(event.getApkUrl());
        }
    }

    private void startDownApk(String url) {
        if (downTask != null) {
            downTask.remove();
        }
        String path = Objects.requireNonNull(getApplication().getExternalFilesDir("")).getAbsolutePath();
        Log.i(TAG, "path=" + path);
        downTask = OkDownload.request(url, OkGo.<File>get(url))
                .folder(path)
                .save()
                .register(new DownloadListener(url) {
                    @Override
                    public void onStart(Progress progress) {
                        Log.i(TAG, "onStart");
                    }

                    @Override
                    public void onProgress(Progress progress) {
                        Log.i(TAG, "onProgress=" + progress.fraction * 100);
                    }

                    @Override
                    public void onError(Progress progress) {
                        Log.i(TAG, "onError " + progress.exception.toString());
                    }

                    @Override
                    public void onFinish(File file, Progress progress) {
                        Log.i(TAG, "onFinish  file=" + file.getPath());
                        installApk(file);
                    }

                    @Override
                    public void onRemove(Progress progress) {
                    }
                });
        downTask.start();
    }

    private void installApk(File file) {
        if (file == null) {
            Log.i("DownApkService", "down apk fail 1");
            return;
        }
        if (!file.exists()) {
            Log.i("DownApkService", "down apk fail 2");
            return;
        }
        EventBus.getDefault().post(new ApkFinishEvent(file));
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (downTask != null) {
            downTask.remove();
        }
        super.onDestroy();
    }

}
